import { Api } from '@/api'
import { useRequest } from '@/hooks/request'
import { useInformationStore } from '@/store/information'
import { ref, watch } from 'vue'

export function useInformations() {
  const Categories = useRequest(Api.DocumentService.GetCategories)
  const Document = useRequest(Api.DocumentService.GetDocumentById)
  const DocumentByVid = useRequest(Api.DocumentService.GetDocumentByVid)

  return {
    Categories,
    Document,
    DocumentByVid,
  }
}

export function useCategory(tag: any) {
  const store = useInformationStore()
  const categories = ref<Eps.DocumentService.GetCategories[0]>(null!)
  const documents = ref<Eps.DocumentService.GetDocuments[]>(null!)
  tag = ref(tag)
  watch([() => store.categories, tag], ([val, newTag]) => {
    if (!val)
      return
    const data = val[newTag]
    categories.value = data
    if (!data?.Items?.length)
      return
    Promise.all(
      data.Items.map(item =>
        Api.DocumentService.GetDocuments({
          pageIndex: 0,
          pageSize: 4,
          channelId: item.Data?.id,
          searchTitle: '',
        }),
      ),
    ).then((res) => {
      documents.value = res.map((item, index) => {
        return {
          ...item,
          categoryName: data?.Items?.[index]?.Data?.Name || '',
        }
      })
    })
  }, {
    immediate: true,
  })

  return {
    documents,
    categories,
  }
}
